package com.syn.michat.service.impl;

import com.syn.michat.constant.ErrorContants;
import com.syn.michat.constant.FriendContants;
import com.syn.michat.mapper.UserMapper;
import com.syn.michat.model.ResponseEntity;
import com.syn.michat.pojo.User;
import com.syn.michat.service.UserService;
import com.syn.michat.util.exception.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUser(String username, String password) throws ClientException {
        User user = userMapper.findByUser(username, password);
        if (user == null) {
            throw new ClientException(ErrorContants.USER_NOTEXIST_OR_PWDINCORRECT, "用户不存在或密码错误", null);
        }
        return user;
    }

    @Override
    public User findUser(String userId) throws ClientException {
        try {
            return userMapper.findUser(userId);
        } catch (Exception e) {
            throw new ClientException(ErrorContants.SQL_INCORRECT, e.getMessage());
        }
    }

    @Override
    public void add(User user) throws ClientException {
        List<User> list = userMapper.findByUsername(user.getUsername());
        if (list.size() == 0) {
            userMapper.add(user);
        } else {
            throw new ClientException(ErrorContants.USER_ALREADY_EXISTS, "用户已被注册");
        }
    }

    @Override
    public User search(String username) throws ClientException {
        try {
            return userMapper.search(username);
        } catch (Exception e) {
            throw new ClientException(ErrorContants.SQL_INCORRECT, e.getMessage());
        }
    }

    @Override
    public void updateNickname(String username, String nickname) throws ClientException {
        try {
            userMapper.updateNickname(username, nickname);
        } catch (Exception e) {
            throw new ClientException(ErrorContants.SQL_INCORRECT, e.getMessage());
        }
    }
}
